package com.fafu.control;

import com.fafu.dao.mapper.WorkerMapper;
import com.fafu.model.Studentrepair;
import com.fafu.pojo.*;
import com.fafu.service.StudentRepairService;
import com.fafu.service.WorkerService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import util.Dictionary;
import util.JsonRsp;
import util.MyMap;

import java.util.*;

import static util.Dictionary.CODE.*;
import static util.Dictionary.REPAIR.*;

@Api("学生报修")
@RestController
@RequestMapping("/repair")
//@CrossOrigin(origins={"127.0.0.1:80"})
public class RepairControl {
    private Logger logger = LoggerFactory.getLogger(RepairControl.class);
    @Autowired
    private StudentRepairService studentRepairService;
    @Autowired
    private WorkerService workerService;
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @ApiOperation("学生报修")
    @RequestMapping(value = "/studentRepair", method=RequestMethod.POST)
    public JsonRsp studentRepair(
            @RequestBody @ApiParam("学生报修信息") StudentRepairInputPojo studentRepairInputPojo
            ,@RequestParam(value = "isAlert", defaultValue = "1") @ApiParam(value = "是否广播")Integer isAlert){
//            @RequestParam(value = "type")@ApiParam("维修类别") Integer type
//            , @RequestBody @Validated Studentrepair studentrepair
//            , BindingResult result
//            , @RequestBody(required = false) ArrayList<Integer>picIdList){

        try{
            Studentrepair studentrepair = new Studentrepair();
            Integer type = studentRepairInputPojo.getType();
            BeanUtils.copyProperties(studentRepairInputPojo,studentrepair);
            List<Integer> picIdList = studentRepairInputPojo.getPicIdList();
//            if(result.hasErrors()){
//                String error = result.getAllErrors().get(0).toString();
//                String[] re = error.split("\\|");
//                return JsonRsp.fail(Integer.parseInt(re[0]),re[1]);
//            }
            Map<String,Object> insertResult = studentRepairService.studentRepair(studentrepair,picIdList);
            Integer code = (Integer) insertResult.get("code");

            if(code.equals( PREPARE_REPAIR_IS_DECLARE)){
                return JsonRsp.fail(IS_DECLARE_REPAIR,"有未处理报修",insertResult.get("data"));
            }else if(code.equals( Dictionary.CODE.IDEN_ERROR)){
                return JsonRsp.fail(IDEN_ERROR,"学号不存在",insertResult.get("data"));
            }
            if(code.equals(PREPARE_REPAIR_SUCCESS)){
                //广播回去，让前端再查
                if(isAlert == 1)
                    messagingTemplate.convertAndSend("/demo_2/topic/getResponse","search");
                return JsonRsp.success(new MyMap().put("id",insertResult.get("data")).toMap(),"success");
            }

        }catch (Exception e){
            logger.error(e.getMessage());
            return JsonRsp.fail(Dictionary.CODE.SYSTEM_ERROR,"系统内部错误");
        }
        return null;//永远进不来
    }

    @ApiOperation("报修查询接口")
    @RequestMapping(value = "/search",method = RequestMethod.GET)
    public JsonRsp search(
              @ApiParam("类别id 0:历史 1:进度")@RequestParam("type") Integer type
            , @ApiParam("学生Id") @RequestParam("sid")Long sid
            ,@ApiParam("第几页")@RequestParam(value = "pageNum", defaultValue = "1")Integer pageNum
            ,@ApiParam("每页几条，默认20")@RequestParam(value = "pageSize",defaultValue = "20")Integer pageSize){
        try{
            List<Integer> stateType = new ArrayList<>();
            Map<String,Object> paramMap = new HashMap<>();
            if(type == null)
                return JsonRsp.fail(Dictionary.CODE.PARAM_IS_LOST,"type为空");
            switch (type){
                case REPAIR_STATE_HISTORY:
                    stateType.add(REPAIR_STATE_HISTORY);
                    paramMap.put("type",stateType);break;
                case Dictionary.REPAIR.REPAIR_STATE_INRUNNING:
                    stateType.add(REPAIR_STATE_NO_READ);
                    stateType.add(REPAIR_STATE_READ);
                    stateType.add(REPAIR_STATE_HANDING);
                    stateType.add(REPAIR_STATE_REFUSE);
                    paramMap.put("type",stateType);
                    break;
                default:return JsonRsp.fail(PARAM_ERROR,"type错误");
            }
            paramMap.put("sid",sid);
            paramMap.put("pageNum",pageNum);
            paramMap.put("pageSize",pageSize);
            Map<String,Object> reMap = studentRepairService.searchList(paramMap);

            return JsonRsp.success(reMap.get("data")).setCount((Long) reMap.get("count"));

        }catch (Exception e){
            logger.error(e.getMessage());
            return JsonRsp.fail(Dictionary.CODE.SYSTEM_ERROR,"系统内部错误");
        }
    }

    @ApiOperation("管理员未读信息查询")
    @RequestMapping(value = "/noReadNum",method = RequestMethod.GET)
    public JsonRsp noReadNum(
            @ApiParam("操作管理员id")@RequestParam("managerId")Integer operationManage){
        try {
            NoReadPojo noReadPojo = studentRepairService.searchNoReadNum(operationManage);
            return JsonRsp.success(noReadPojo);
        }catch (Exception e){
            logger.error("内部异常"+e);
            return JsonRsp.fail(SYSTEM_ERROR,"系统内部错误");
        }
    }

    @ApiOperation("管理员未读信息查询List")
    @RequestMapping(value = "/noReadList",method = RequestMethod.GET)
    public JsonRsp noReadList(
            @ApiParam("操作管理员id")@RequestParam("managerId")Integer operationManage
            ,@ApiParam("类别")@RequestParam("type")Integer type
            ,@ApiParam("第几页")@RequestParam(value = "pageNum", defaultValue = "1")Integer pageNum
            ,@ApiParam("每页几条，默认20")@RequestParam(value = "pageSize",defaultValue = "20")Integer pageSize){
        try {
            Map<String,Object> reMap= studentRepairService.searchNoReadList(operationManage,type,pageNum,pageSize);
            return JsonRsp.success(reMap.get("data")).setCount((Long) reMap.get("count"));
        }catch (Exception e){
            logger.error("内部异常"+e);
            return JsonRsp.fail(SYSTEM_ERROR,"系统内部异常");
        }
    }

    @ApiOperation("管理员未读信息查询List")
    @RequestMapping(value = "/repairNoReadItem",method = RequestMethod.GET)
    public JsonRsp noReadItem(
            @ApiParam("itemId")@RequestParam("itemId")Integer itemId
            ,@ApiParam("类别0:学生报修，1：其他问题")@RequestParam("type")Integer type){
        try{
            Map<String,Object> remap = studentRepairService.searchItem(itemId,type);
            Object data = remap.get("data");
            NoReadPojoAndWorkerList redata = new NoReadPojoAndWorkerList();
            List relist = workerService.searchWorkerList(new MyMap().put("key","").toMap());
            redata.setData(data);
            redata.setWorkerList(relist);
            if(data == null)
                return JsonRsp.fail(NOT_KOWN_ERROR,"未知错误");
            return JsonRsp.success(redata);
        }catch (Exception e){
            logger.error("内部异常"+e);
            return JsonRsp.fail(SYSTEM_ERROR,"系统内部异常");
        }
    }

    @ApiOperation("管理员查询进行时或历史")
    @RequestMapping(value = "/repairROHIem",method = RequestMethod.GET)
    public JsonRsp repairROHIem(
            @ApiParam("itemId")@RequestParam("itemId")Integer itemId
            ,@ApiParam("类别0:历史，3：进行中 4拒绝")@RequestParam("type")Integer type) {
        try {
            Map<String,Object> reMap =studentRepairService.searchROHItem(itemId,type);
            return JsonRsp.success(reMap.get("data"));
        } catch (Exception e) {
            logger.error("内部异常" + e);
            return JsonRsp.fail(SYSTEM_ERROR, "系统内部异常");
        }
    }

    @ApiOperation("管理员查询拒绝的list")
    @RequestMapping(value = "/refuseList",method = RequestMethod.GET)
    public JsonRsp refuseList(
            @ApiParam("operationId")@RequestParam("operationId")Integer operationId
            ,@ApiParam("type:默认0：全部，1：自己")@RequestParam(value = "type",defaultValue = "0",required = false)Integer type
            ,@ApiParam("第几页")@RequestParam(value = "pageNum", defaultValue = "1")Integer pageNum
            ,@ApiParam("每页几条，默认20")@RequestParam(value = "pageSize",defaultValue = "20")Integer pageSize) {
        try{
            MyMap paramMap = new MyMap().put("operationId",operationId);
            if(type == 1)
                paramMap.put("type","1");
            Map<String,Object> reMap= studentRepairService.searchRefuseList(paramMap.put("pageNum",pageNum).put("pageSize",pageSize).toMap());
            return JsonRsp.success(reMap.get("data")).setCount((Long) reMap.get("count"));
        }catch (Exception e){
            logger.info(""+e);
            return JsonRsp.fail(SYSTEM_ERROR,"system error");
        }
    }
    @ApiOperation("管理员查询拒绝的Item")
    @RequestMapping(value = "/refuseItem",method = RequestMethod.GET)
    public JsonRsp refuseItem(
            @ApiParam("itemId")@RequestParam("itemId")Integer itemId) {
        try{
            MyMap paramMap = new MyMap().put("itemId",itemId);
            Map<String,Object> reMap= studentRepairService.searchRefuseItem(paramMap.toMap());
            return JsonRsp.success(reMap.get("data"));
        }catch (Exception e){
            logger.info(""+e);
            return JsonRsp.fail(SYSTEM_ERROR,"system error");
        }
    }
    @ApiOperation("维修结束")
    @RequestMapping(value = "/repairEnd",method = RequestMethod.GET)
    public JsonRsp repairEnd(
            @ApiParam("itemId")@RequestParam("itemId")Integer itemId) {
        try{
            MyMap paramMap = new MyMap().put("itemId",itemId);
            Map<String,Object> reMap= studentRepairService.repairEnd(paramMap.toMap());
            return JsonRsp.success(reMap.get("data"));
        }catch (Exception e){
            logger.info(""+e);
            return JsonRsp.fail(SYSTEM_ERROR,"system error");
        }
    }
    @ApiOperation("维修结束")
    @RequestMapping(value = "/repairOtherEnd",method = RequestMethod.GET)
    public JsonRsp repairOtherEnd(
            @ApiParam("itemId")@RequestParam("itemId")Integer itemId) {
        try{
            MyMap paramMap = new MyMap().put("itemId",itemId);
            Map<String,Object> reMap= studentRepairService.repairOtherEnd(paramMap.toMap());
            return JsonRsp.success(reMap.get("data"));
        }catch (Exception e){
            logger.info(""+e);
            return JsonRsp.fail(SYSTEM_ERROR,"system error");
        }
    }
}
